package org.gruposp2p.cometd;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import org.codehaus.groovy.grails.commons.ApplicationHolder;
import org.cometd.bayeux.Bayeux;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class LazySpringBayeuxInitializer 
	implements ServletContextAttributeListener {

    private final Logger logger = LoggerFactory.getLogger(LazySpringBayeuxInitializer.class);

    public static final String BAYEUX_ATTRIBUTE ="org.cometd.bayeux";
    
    public void attributeAdded(ServletContextAttributeEvent event) {
        if (BAYEUX_ATTRIBUTE.equals(event.getName())) {
            Bayeux bayeux = (Bayeux) event.getValue();
            BayeuxHolder.setBayeux(bayeux);
            ApplicationContext context = (ApplicationContext)ApplicationHolder
                    .getApplication().getMainContext();
            // Trigger CometD service initialization
            context.getBean("karmaMessageService");
            /*String [] beans = context.getBeanDefinitionNames();
            for (int i = 0; i < beans.length; i++) {
            	logger.debug(beans[i]);
            }*/
        }
    }

    public void attributeRemoved(ServletContextAttributeEvent event) {
    	logger.debug("attributeRemoved - ServletContextAttributeEvent - " + event.getName());
    }

    public void attributeReplaced(ServletContextAttributeEvent event) { 
    	logger.debug("attributeReplaced - ServletContextAttributeEvent - " + event.getName());
    }
    
}